#!/bin/bash

set -e

# source the common build functions
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
source "${SCRIPT_DIR}/ios_build_functions.sh"

function setup ()
{
    if [ "${INSTALL_PATH}/lib/libgit2.a" -nt "${ROOT_PATH}/External/libgit2" ]
    then
        echo "No update needed."
        exit 0
    fi

    LIBRARY_NAME="libgit2"
}

function build_libgit2 ()
{

    # Force CMake to rebuild
    rm -rf "${ARCH_INSTALL_PATH}/libgit2"

    mkdir -p "${ARCH_INSTALL_PATH}/libgit2"
    pushd "${ARCH_INSTALL_PATH}/libgit2" > /dev/null

    # LOL Cmake
    SYS_ROOT="-DCMAKE_OSX_SYSROOT=${SDKROOT}"

    # We only want to discover our static library
    export PKG_CONFIG="${SCRIPT_DIR}"/pkg-config-static

    # Limit pkg-config to what we're currently expecting it to use
    # PKG_CONFIG_PATH="${INSTALL_PATH}/lib/pkgconfig/"
    # LDFLAGS="-L $(xcrun --sdk iphoneos --show-sdk-path)/usr/lib"
    # export PKG_CONFIG_PATH
    # export LDFLAGS

    cmake \
        -DCMAKE_C_COMPILER_WORKS:BOOL=ON \
        -DBUILD_SHARED_LIBS:BOOL=OFF \
        -DCMAKE_PREFIX_PATH:PATH="${INSTALL_PATH}/" \
        -DPKG_CONFIG_USE_CMAKE_PREFIX_PATH:BOOL=ON \
        -DCMAKE_INSTALL_PREFIX:PATH="${ARCH_INSTALL_PATH}/" \
        -DBUILD_CLAR:BOOL=OFF \
        -DTHREADSAFE:BOOL=ON \
        -DCURL:BOOL=OFF \
        -DCMAKE_C_FLAGS:STRING="-fembed-bitcode" \
        "${SYS_ROOT}" \
        -DCMAKE_OSX_ARCHITECTURES:STRING="${ARCH}" \
        "${ROOT_PATH}/External/libgit2" >> "${LOG}" 2>&1
    cmake --build . --target install >> "${LOG}" 2>&1
    popd > /dev/null

    # push the built library into the list
    BUILT_LIB_PATHS+=("${ARCH_INSTALL_PATH}/lib/libgit2.a")
}

function fat_binary ()
{
    echo "Building fat binary..."

    lipo -create "${BUILT_LIB_PATHS[@]}" -output "${INSTALL_PATH}/lib/libgit2.a"

    echo "Building done."
}

build_all_archs setup build_libgit2 fat_binary
